//data储存分页，数据条数信息
let pageData = {
	//当前页
	currentPage: 1,
	//每页数据条数
	pageSize: 5,
	//先存着，页面初始渲染会赋值
	totalPage: 0,
	totalStudent: 0,
	//先存着，type默认为name,
	searchType: 'name',
	searchValue: '',
}

//获取所有学生信息
getStudents();

//获取所有学生信息
function getStudents() {
	$.ajax({
		url: '/students/getStudents',
		type: 'get',
		data: {
			...pageData
		},
		success(res) {
			console.log(res);
			if (res.status) {
				//渲染学生信息函数
				renderStudents(res.data);
			} else { renderStudents() }
		}
	});
}

//搜索值(type,value)检测--学生搜索
$('#searchType').change(function () {
	const searchType = $('#searchType').val();
	pageData.searchType = searchType;
	console.log(pageData);
})
$('#searchValue').change(function () {
	const searchValue = $('#searchValue').val();
	pageData.searchValue = searchValue;
	console.log(pageData);
})

//学生搜索--模糊查询
$('#searchBtn').click(function () {
	//⭐搜索前需要将页码改为1
	pageData.currentPage = 1;
	console.log('搜索前：', searchType, pageData)

	$.ajax({
		url: 'students/getStudents',
		type: 'get',
		data: {
			...pageData,
		},
		success(res) {
			if (res.status) {
				console.log('搜索返回', res);
				renderStudents(res.data);
			} else {
				alert(res.message)
			}
		}
	})
})

// 渲染学生列表 与 分页信息
function renderStudents(data) {
	//data要求为数组
	//获取学生 table
	const studentsInfo = $('tbody#studentsInfo');
	//获取分页相关信息
	const currentPage = $('#currentPage');
	const totalPage = $('#totalPage');
	const totalStudent = $('#totalStudent');

	//现在页渲染
	currentPage.text(pageData.currentPage);
	//总页数渲染
	totalPage.text(data.totalPage);
	//数据总条数渲染
	totalStudent.text(data.totalStudent);
	//存入本地
	pageData.totalPage = data.totalPage;
	pageData.totalStudent = data.totalStudent;

	if (data.students.length) {
		const str = data.students.map(item => {
			//修改和删除按钮绑定ID
			return `
				<tr>
					<td>
						<img id='stuImage' src="./img/${item.imagesName || 'defaultImg.jpg'} " alt="StuImages">
					</td>
					<td>${item.name}</td>
					<td>${item.age}</td>
					<td>${item.gender}</td>
					<td>${item.classId.name}</td>
					<td>
						${(item.classId.teachers).map(item => {
				return `<span>${item.name}</span><br>`
			}).join('')}
					</td>
					<td>
						<input type='button' value='修改' 
						class='upgradeBtn' data-id='${item._id}' />
						<input type='button' value='删除' id='deleteBtn' data-id='${item._id}'/>
					</td>
				</tr>
			`
		}).join('');
		studentsInfo.html(str)
	}
	else {
		studentsInfo.html(`
			<tr>
				<td colspan='6' style='text-align:center;'>搜索信息不存在<td/>
			</tr>
		`)
	}
}

//新增学生
$('#addStudentBtn').click(function () {
	const name = $('#studentName').val();
	const age = $('#studentAge').val();
	//被选中的单选框;
	const gender = $("input[name=studentGender]:checked").val();
	//被选中的班级
	const classId = $("#classList").val();
	//图片信息
	const imagesName = $('#stuImageUpload').data('filename');

	$.ajax({
		url: '/students/addStudent',
		type: 'post',
		data: {
			name,
			age,
			gender,
			classId,
			imagesName
		},
		success(res) {
			//成功就清除历史，并提示，并在此获取学生信息
			if (res.status) {
				alert('添加学生信息成功！')
				getStudents();
				// $('#studentName').val('');
				// $('#studentAge').val('');
				// $("input[name=studentGender]:checked").prop('checked',false);
				$('#stuImageUpload').prop('src', './img/defaultImg.jpg');
				$('#stuImageUpload').data('filename', '');
			} else {
				alert(res.message)
			}
		}
	})
})

//修改学生(预)--从列表获取学生信息并渲染修改区--事件委托
$('tbody').on('click', '.upgradeBtn', function (e) {
	//因为列表里面的修改按钮是动态生成的，需要事件委托，才能绑定事件
	//修改学生--获取修改区input
	const upgradeName = $('#upgradeName');
	const upgradeAge = $('#upgradeAge');
	const upgradeMale = $('#upgradeMale');
	const upgradeFemale = $('#upgradeFemale');
	const upgradeStuInfoBtn = $('#upgradeStuInfoBtn');

	//标签自定义的属性获值
	const _id = $(this).data('id');

	$.ajax({
		url: '/students/_id',
		type: 'get',
		data: {
			_id,
		},
		success(res) {
			console.log(res);
			if (res.status) {
				upgradeName.val(res.data.name);
				upgradeAge.val(res.data.age);
				upgradeStuInfoBtn.attr('data-id', _id)
				if (res.data.gender === 'male') upgradeMale.prop('checked', true);
				else upgradeFemale.prop('checked', true);
				$('#stuImageUpgrade').prop('src', `./img/${res.data.imagesName || 'defaultImg.jpg'} `);
				$('#stuImageUpgrade').data('filename', `${res.data.imagesName}`);
			}
		}
	})
})

//修改学生（真）
$('#upgradeStuInfoBtn').click(e => {
	const upgradeName = $('#upgradeName').val();
	const upgradeAge = $('#upgradeAge').val();
	const upgradeGender = $("input[name='upgradeGender']:checked").val();
	const _id = (e.target).getAttribute('data-id');
	const upgradeClassId = $('#upgradeClassList').val();
	//获取图片 filename
	const imagesName = $('#stuImageUpgrade').data('filename');

	$.ajax({
		url: '/students/upgradeStuInfo',
		type: 'post',
		data: {
			_id,
			name: upgradeName,
			age: upgradeAge,
			gender: upgradeGender,
			classId: upgradeClassId,
			imagesName
		},
		success(res) {
			if (res.status) {
				alert(res.message);
				getStudents();
				$('#upgradeName').val('');
				$('#upgradeAge').val('');
				$("input[name=upgradeGender]:checked").prop('checked', false);
				$('#stuImageUpgrade').prop('src', './img/defaultImg.jpg');
				$('#stuImageUpgrade').data('filename', '');
			} else {
				alert(res.message);
			}

		}
	})
})

//删除学生
$('tbody').on('click', '#deleteBtn', e => {
	const _id = (e.target).getAttribute('data-id');
	$.ajax({
		url: '/students/deleteStudent',
		type: 'get',
		data: {
			_id
		},
		success(res) {
			if (res.status) {
				//删除优化，解决最后一页只剩一条数据，删除后退回上一页
				if (pageData.totalStudent % pageData.pageSize === 1) {
					pageData.currentPage--;
					alert(res.message);
					getStudents();
				} else {
					alert(res.message);
					getStudents();
				}
			} else {
				alert('删除发生意外，请刷新页面检测是否成功！')
			}
		}
	})
})

//分页功能
//改变数据条数
$('#pageSize').change(function (e) {
	pageData.pageSize = e.target.value;
	pageData.currentPage = 1;
	getStudents();
})
//下一页
$('#nextBtn').click(e => {
	if (pageData.currentPage < pageData.totalPage) {
		pageData.currentPage++;
		getStudents();
	} else {
		alert('尾页了，已无下一页！')
	}
})
//上一页
$('#prevBtn').click(e => {
	if (pageData.currentPage > 1) {
		pageData.currentPage--;
		getStudents();
	} else {
		alert('首页了，已无上一页！')
	}
})
//首页
$('#firstPageBtn').click(function () {
	pageData.currentPage = 1;
	getStudents();
})
//尾页
$('#lastPageBtn').click(function () {
	pageData.currentPage = pageData.totalPage;
	getStudents();
})



